package com.atcd.springcloud.controller;

import com.atcd.springcloud.entities.Payment;
import com.atcd.springcloud.entities.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import com.atcd.springcloud.service.PaymentService;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@CrossOrigin
public class PaymentController {
    @Resource
    private PaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    //使用post请求得到参数的时候，要使用RequestBody或者requestParam得到参数
    @PostMapping("/payment/create")
    public ResponseResult<Payment> create(@RequestBody Payment payment){
        log.info("访问的数据{}",payment);
        int result = paymentService.create(payment);
        log.info("************插入结果************: "+result);
        return result>0? new ResponseResult(200,"插入数据库成功,port: "+serverPort):new ResponseResult<>(444,"插入数据库失败");
    }

    //restful风格
    @GetMapping("/payment/get/{id}")
    public ResponseResult<Payment> get(@PathVariable("id") Long  id){
        Payment select = paymentService.select(id);
        log.info("************插入结果************: "+select);
        return !Objects.isNull(select)? new ResponseResult(200,"查询成功,port: "+serverPort,select):
                new ResponseResult<>(444,"查询失败,没有对应的id:"+id,null);
    }

    //手写轮训算法
    @GetMapping(value = "/payment/lb")
    public String getPaymentLB(){
        return serverPort;
    }


    @GetMapping("/payment/feign/timeout")
    public String paymentFeignTimeout(){
        //暂停几秒钟线程
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return serverPort;
    }
}
